/*
 * Copyright 2011 Kim Lindhardt Madsen
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package dk.lindhardt.gwt.geie.client.evaluate;

import org.matheclipse.parser.client.Parser;
import org.matheclipse.parser.client.ast.ASTNode;
import org.matheclipse.parser.client.ast.FunctionNode;
import org.matheclipse.parser.client.ast.SymbolNode;

import java.util.Set;

/**
 * User: AnAmuser
 * Date: 24-08-11
 * <p/>
 *
 */
public class GeieVariableHelper {

   /**
    * Get the variable names from the given expression.
    *
    * @param expression
    *          an expression to parse
    * @param result
    *          a set which contains the variable names
    */
   public static void getVariables(String expression, Set<String> result) {
      Parser p = new Parser(true);
      ASTNode node = p.parse(expression);
      getVariables(node, result);
   }

   /**
    * Get the variable names from the given AST node.
    *
    * @param node
    *          an already parsed AST node
    * @param result
    *          a set which contains the variable names
    */
   public static void getVariables(final ASTNode node, Set<String> result) {
      if (node instanceof FunctionNode) {
         FunctionNode functionNode = (FunctionNode) node;
         if (functionNode.size() > 0
               && functionNode.getNode(0) instanceof SymbolNode) {
            for (int i = 1; i < functionNode.size(); i++) {
               getVariables(functionNode.getNode(i), result);
            }
         }
      }
      if (node instanceof SymbolNode) {
         Object obj = GeieDoubleEvaluator.SYMBOL_DOUBLE_MAP.get(node.toString());
         if (obj == null) {
            obj = GeieBooleanEvaluator.SYMBOL_BOOLEAN_MAP.get(node.toString());
            if (obj == null) {
               result.add(node.toString());
            }
         }

      }
   }
}
